<template>
  <div class="add-container">
    <!-- 头部的面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 一个卡片区域 -->
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="success" center show-icon :closable="false"> </el-alert>
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="商品完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="100px" label-position="top">
        <!-- tab栏 -->
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cascaderProp" @change="cateChange" clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(param, index) in item.attr_vals" :key="index" :label="param" size="small" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="upLoadSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" />
            <el-button type="primary" style="margin-top:15px" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewURL" alt="图片飞了" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created() {
    this.getCateList()
    console.log(this.addForm, '初始时')
  },
  data() {
    return {
      activeIndex: 0,
      cateList: [],
      manyList: [], // 存储动态参数列表
      onlyList: [], // 存储静态属性列表
      /* 图片预览对话框相关设置 */
      dialogVisible: false,
      /* 添加表单相关设置 */
      // 添加表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [], // 存放商品分类的id值
        pics: [], // 存储商品图片路径
        goods_introduce: '', // 商品的详情介绍
        attrs: [] // 存储动态参数和动态属性
      },
      // 添加表单的验证规则
      addFormRule: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      /* 级联组件相关设置 */
      cascaderProp: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      /* 上传组件相关设置 */
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewURL: ''
    }
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败!')
      this.cateList = res.data
    },
    /* 级联组件绑定函数 */
    // 当分类切换时触发
    cateChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      // console.log(this.addForm.goods_cat)
    },
    /* Tab组件相关绑定函数 */
    // 切换tab时触发，返回false将会被阻止切换
    beforeTabLeave(toAciveName, fromActiveName) {
      if (fromActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        return false
      }
    },
    // tab点击事件
    async tabClick() {
      // 如果当前为商品参数
      if (this.activeIndex === '1') {
        this.getManyOrOnlyList('many')
      } else if (this.activeIndex === '2') {
        this.getManyOrOnlyList('only')
      }
    },
    // 封装获取动态参数或者静态属性函数
    async getManyOrOnlyList(type) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: type }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败!')
      if (type === 'many') {
        // 将attr_vals里面参数用数组保存起来
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyList = res.data
        console.log(this.manyList, 'many')
      } else {
        this.onlyList = res.data
        console.log(this.onlyList, 'only')
      }
    },
    /* 上传组件相关事件处理 */
    // 处理图片预览
    handlePreview(file) {
      this.previewURL = file.response.data.url
      this.dialogVisible = true
    },
    // 处理图片删除
    handleRemove(file) {
      // 获取要删除图片的临时路径
      const filePath = file.response.data.tem_path
      // 获取该临时路径再数组中的下标
      const index = this.addForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      // 再数组中删除该下标值的路径
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics, '移除图片')
    },
    // 上传成功时会被触发
    upLoadSuccess(response) {
      const picPath = {
        // 获取上传成功后返回来的图片的临时路径
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picPath)
      console.log(this.addForm.pics, '上传图片')
    },
    /* 添加商品响应事件 */
    async addGood() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('你有选项未填!')
        // 数据处理
        // 对addForm进行深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 对动态参数进行处理
        this.manyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 对静态参数进行处理
        this.onlyList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(this.addForm, '原表单')
        console.log(form, '处理过后的表单')
        // 发送至服务器
        const { data: res } = await this.$http.post('goods', form)
        console.log(res, '服务器返回')
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>
